﻿using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

namespace TimeCapsule
{
	public partial class BlogRead : System.Web.UI.Page
	{
		#region Variables
		public int PageCount
		{
			get
			{
				object o = this.ViewState["_PageCount"];
				if (o == null)
					return 0;
				else
					return (int)o;
			}
			set
			{
				this.ViewState["_PageCount"] = value;
			}
		}
		public int CurrentPage
		{
			get
			{
				object o = this.ViewState["_CurrentPage"];
				if (o == null)
					return 0;
				else
					return (int)o;
			}
			set
			{
				this.ViewState["_CurrentPage"] = value;
			}
		}
		#endregion
		
		public static int pageSize = 5;
		public static int[] BindedPage = new int[pageSize];
		public static Member mb;
		
		protected void Page_Load(object sender, EventArgs e)
		{
			Page.ClientScript.RegisterHiddenField("hdnCurrent", "-1");
			Page.ClientScript.RegisterHiddenField("ActivePostIdx", "-1");
			Page.ClientScript.RegisterHiddenField("hdnReplyPassword", "-1");
			Page.ClientScript.RegisterHiddenField("hdnReplyIdx", "-1");
			
			if(!IsPostBack)
			{
				mb = new Member();
				Page.ClientScript.RegisterHiddenField("hdnLoginId", mb.Idx.ToString());
				if( !string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["page"]) )
					CurrentPage = int.Parse(HttpContext.Current.Request.QueryString["page"].ToString());
				BindBlog();
			}
		}
		
		/// <summary>
		/// 블로그 게시글 바인딩
		/// </summary>
		void BindBlog()
		{
			Util a = new Util();
			dbAccess da = new dbAccess();
			
			PagedDataSource pds = new PagedDataSource();
			pds = da.BindBlog( pageSize );
			pds.CurrentPageIndex = CurrentPage;

			btnPrev.Enabled = !pds.IsFirstPage;
			btnNext.Enabled = !pds.IsLastPage;
			
			dlBlog.DataSource = pds;
			dlBlog.DataBind();
			
			if ((int)mb.Role == 1)								//관리자
				divAdminWrite.Visible = true;
			
 			DataView dv = (DataView)pds.DataSource;
			string[] arrIdx = new string[pageSize];
			
			for (int i=0; i<pageSize; i++)
			{
				if( dv.Table.Rows.Count - (pageSize * pds.CurrentPageIndex) - i > 0 )
				{
					
				}
			}
			
			for( int i=0; i<pageSize; i++)
			{
				if( pageSize * ( pds.CurrentPageIndex + 1 ) - i - 1 < dv.Table.Rows.Count )
				{
					BindedPage[i] = int.Parse(dv.Table.Rows[pageSize * (pds.CurrentPageIndex + 1) - i - 1]["Idx"].ToString());
					BindBlogReply(int.Parse(dv.Table.Rows[pageSize * (pds.CurrentPageIndex + 1) - i - 1]["Idx"].ToString()), pageSize - i - 1);
				}
			}
		}
		
		/// <summary>
		/// Reply Binding Fucntion
		/// Page -> 댓글이 달리는 게시글 번호
		/// Ctr -> 댓글 바인딩하는 DataList ID의 뒷 번호
		/// </summary>
		/// <param name="Page"></param>
		/// <param name="Ctr"></param>
		void BindBlogReply( int Page, int Ctr )
		{	
			if( Ctr > pageSize)
				return;
			dbAccess da = new dbAccess();
			
			PagedDataSource pds = new PagedDataSource();
			pds = da.BindBlogReply(Page, 100);

			pds.CurrentPageIndex = 0;

			Repeater dlBlogReply = dlBlog.Controls[Ctr].FindControl("dlBlogReply") as Repeater;
			dlBlogReply.DataSource = pds;
			dlBlogReply.DataBind();
		}

		void BindBlogReply( int Page, Repeater rpt )
		{
			dbAccess da = new dbAccess();
			PagedDataSource pds = new PagedDataSource();
			pds = da.BindBlogReply(Page, 100);
			pds.CurrentPageIndex = 0;
			rpt.DataSource = pds;
			rpt.DataBind();
		}

		protected void Test(object sender, EventArgs e)
		{
			System.Diagnostics.Debug.WriteLine("TEST");
		}
	
		protected void btnWriteRpl_Clicked(object sender, RepeaterCommandEventArgs e)
		{
			switch(e.CommandName.ToString())
			{
				case "WriteReply":
					WriteReply(e.Item);
					break;
				case "DeleteReply":
					DeleteReply(e.Item);
					break;
				default :
					return;
			}
		}
		
		protected void WriteReply(RepeaterItem item)
		{
 			int Idx = int.Parse(Request.Form.Get("ActivePostIdx"));
			
			TextBox txtId = item.FindControl("txtReplyId") as TextBox;
			Label lblId = item.FindControl("lblReplyId") as Label;
			TextBox txtBody = item.FindControl("txtReplyBody") as TextBox;
			TextBox txtPsw = item.FindControl("txtReplyPsw") as TextBox;
			
			dbAccess da = new dbAccess();
			da.BlogRplWrite(txtId.Visible ? txtId.Text : lblId.Text, txtBody.Text, txtPsw.Text, Idx, false, mb.Idx);
			BindBlogReply(Idx, (Repeater)item.Parent);
		}
		
		public bool DeleteButtonVisible( string Idx, bool member )
		{
			if( mb.Role == Role.admin || mb.Role == Role.master )
				return true;
				
			if( mb.key == "" )		//비회원
			{
				if( Idx == "-1" )
					return member ? false : true;
				else
					return member ? true : false;
			}
			else			//회원
			{
				if( Idx == mb.Idx.ToString() )
					return member ? true : false;
				else
					return member ? false : true;
			}
		}
		
		protected void DeleteReply(RepeaterItem item)
		{
			string psw = Request.Form.Get("hdnReplyPassword");
			int idx = int.Parse(Request.Form.Get("hdnReplyIdx"));
			int postIdx = int.Parse(Request.Form.Get("ActivePostIdx"));
			
			mb = new Member();
			dbAccess da = new dbAccess();
			
			if(string.IsNullOrEmpty(mb.key))
			{
				if( da.DeactivateReply(idx, psw) )
					BindBlogReply(postIdx, (Repeater)item.Parent);
				else
					ScriptManager.RegisterStartupScript(item.Parent.Parent.Parent, item.Parent.Parent.Parent.GetType(), "Exception", "OpenErrorPopup('dlgErrorWrongPassword')", true);
			}
			else
			{
				if( da.DeactivateReply(mb.Idx, idx, mb.Role) )
					BindBlogReply(postIdx, (Repeater)item.Parent);
				else
					ScriptManager.RegisterStartupScript(item.Parent.Parent.Parent, item.Parent.Parent.Parent.GetType(), "Exception", "OpenErrorPopup('dlgErrorWrongAccess')", true);
			}
			
		}

		protected void PrevPage(object sender, EventArgs e)
		{
			Response.Redirect("BlogRead.aspx?page=" + --CurrentPage);
			// 			CurrentPage -= 1;
			// 			BindBlog();
		}

		protected void NextPage(object sender, EventArgs e)
		{
			Response.Redirect("BlogRead.aspx?page=" + ++CurrentPage);
			// 			CurrentPage += 1;
			// 			BindBlog();
		}
// 		protected void DeleteReply(object sender, EventArgs e)
// 		{
// 			dbAccess da = new dbAccess();
// 			string password = Request.Form.Get("txtReplyPassword");
// 			int idx = int.Parse(Request.Form.Get("hdnReplyIdx"));
// 			
// 			if( mb.Role == 1 )							//관리자인 경우
// 				da.DeactivateReply(idx);
// 			else if( mb.key != "" )						//로그인한 사용자인 경우
// 				da.DeactivateReply(mb.Idx, idx);
// 			else if( mb.key == "" )						//비회원인 경우(비밀번호 확인)
// 				da.DeactivateReply(idx, password);
// 			else
// 				return;
// 			
// 			Response.Redirect("~/BlogRead.aspx");
// 		}

// 		
// 		protected void ReplyButtonClicked(object sender, DataListCommandEventArgs e)
// 		{
// 			switch(e.CommandName.ToString())
// 			{
// 				case "deleteReply":
// 					//DeleteReply();
// 					break;
// 				default :
// 					return;
// 			}
// 		}
		
	}
}
